﻿using SimpleServiceBus.Bus.MessageManagement;
using SimpleServiceBus.Bus.Pipeline;

namespace SimpleServiceBus.Bus
{
    public class MessageRetryErrorHandler : IMessageProcessingErrorHandler
    {
        public virtual bool HandleMessageProcessingError(ref MessageProcessingException exception, MessageEnvelope message, IMessageBus messageBus)
        {
            if (exception.FailedMessage != null)
            {
                if (exception.FailedMessage.RetryCount < messageBus.Endpoint.Metadata.MaxMessageRetryCount)
                {
                    exception.FailedMessage.RetryCount += 1;
                    messageBus.SendLocal(exception.FailedMessage);
                }
                else if (messageBus.Endpoint.Metadata.PoisonMessageAddress != null)
                {
                    messageBus.Send(exception.FailedMessage, messageBus.Endpoint.Metadata.PoisonMessageAddress);
                }
            }

            return true;
        }
    }
}
